package com.wcz.code.util;

import java.awt.Image;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.imageio.ImageIO;

import org.apache.log4j.Logger;

import com.google.gson.Gson;

/**
 * @author 伪尘子
 *
 * 2012-6-18
 */
public class Common {
	
	private static Map<String,Integer> filedarray=null;//日期字段Map
	private static Logger _log=Logger.getLogger(Common.class);
	static{
		if(empty(filedarray)){
			filedarray=new HashMap<String,Integer>();
			filedarray.put("year", Calendar.YEAR);
			filedarray.put("month",Calendar.MONTH);
			filedarray.put("day", Calendar.DATE);
			filedarray.put("hour", Calendar.HOUR);
			filedarray.put("hourofday", Calendar.HOUR_OF_DAY);
			filedarray.put("minute", Calendar.MINUTE);
			filedarray.put("second", Calendar.SECOND);
			filedarray.put("millisecond", Calendar.MILLISECOND);
		}
	}
	
	/**
	 * 获取图像
	 * @param path 路径从根路径下开始
	 * @return
	 * @throws IOException
	 */
	public static Image readImage(String path) {
		try {
			return ImageIO.read(getResourceAsStream(path));
		} catch (IOException e) {
			
			return null;
		}
	}
	
	/**
	 * 获取输入流
	 * @param path 路径从根路径下开始
	 * @return
	 */
	public static InputStream getResourceAsStream(String path){
		return Class.class.getResourceAsStream(path);
	}
	
	
	/**
	 * 获取格式化的日期字符串
	 * @return
	 */
	public static String getDate(){
		
		return getDate(new Date(),null);
	}
	
	/**
	 * 获取时间日期中的字段
	 * @param date
	 * @param filed 
	 * 		  year,month,day,hour,hourofday,minute,second,millisecond
	 * @return
	 */
	public static int getDateFiled(Date date,String filed){
		
		Calendar calendar=Calendar.getInstance();
		if(date!=null){
			calendar.setTime(date);
		}
		
		if(inarray(filed, filedarray)){
			int filedNumber=filedarray.get(filed);
			return calendar.get(filedNumber);
		}
		return 0;
	}
	
	/**
	 * 获取格式化的日期字符串
	 * @param dateFormate
	 * @return
	 */
	public static String getDate(String dateFormate){
		
		return getDate(new Date(),dateFormate);
	}
	
	/**
	 * 获取格式化的日期字符串
	 * @param date
	 * @param dateFormate
	 * @return
	 */
	public static String getDate(Date date,String dateFormate){
		
		SimpleDateFormat dateformate=null;
		dateformate=empty(dateFormate) ? new SimpleDateFormat():new SimpleDateFormat(dateFormate);
		return dateformate.format(date);
		
	}
	
	
	/**
	 * 获取新的日期时间
	 * @param date
	 * @param filedlist 日期字段JSON字符串
	 * 					year,month,day,hour,hourofday,minute,second,millisecond
	 * 					{"year":2012,"month":12}
	 * @return
	 */
	public static Date changeDate(Date date,String filedlist){
		
		Calendar calendar=Calendar.getInstance();
		if(!empty(date)) {
			calendar.setTime(date);
		}
		Map<String,Integer> filed=JSONHelper.parseJSON(filedlist,Map.class);
		if(!empty(filed)){
			for(String key:filed.keySet()){
				
				if(inarray(key,filedarray)){
					//将添加的日期字段，放入到日期calendar中
					calendar.set(filedarray.get(key), filed.get(key));
				}
			}
			
		}
		System.out.println(calendar.get(Calendar.MILLISECOND));
		System.out.println(getDate(calendar.getTime(),"yyyy-MM-dd hh:mm:ss:SSS"));
		return calendar.getTime();
	}
	
	/**
	 * 判断对象是否在数组或集合中
	 * @param obj
	 * @param array
	 * @return
	 */
	public static boolean inarray(Object obj,Object array){
		return inarray(obj, array,false);
	}
	
	
	/**
	 * 判断对象是否在数组或集合中
	 * @param obj
	 * @param array 数组、集合
	 * @param validatetype
	 * @return
	 */
	public static boolean inarray(Object obj,Object array,boolean validatetype){
		if(array==null || obj==null){
			return false;
		}
		if(array instanceof Collection){
			
			for(Object o:((Collection)array)){
				
				if(o.toString().equals(obj.toString())){
					if(validatetype){
						return o.getClass().getName().equals(obj.getClass().getName());
					}
					return true;
				}
			}
		}
		else if(array instanceof Map){
			return ((Map)array).get(obj)!=null;
		}
		else if(array instanceof Object[]){
			
			for(Object o:((Object[])array)){
				if(o.toString().equals(obj.toString())){
					if(validatetype){
						return o.getClass().getName().equals(obj.getClass().getName());
					}
					return true;
				}
			}
			
		}
		
		return false;
	}
	
	/**
	 * 判断对象是否为空
	 * @param o
	 * @return
	 */
	public static boolean empty(Object o){
		if(o==null){
			return true;
		}
		if(o instanceof String){
			return o=="";
		}
		else if(o instanceof Number){
			return ((Number)o).doubleValue()==0;
		}
		else if(o instanceof Boolean){
			return !(Boolean)o;
		}
		else if(o instanceof Collection){
			return ((Collection)o).isEmpty();
		}
		else if(o instanceof Map){
			return ((Map)o).isEmpty();
		}
		else if(o instanceof Object[] ){
			return ((Object[])o).length==0;
		}
		
		return false;
	}
	
	
	/**
	 * 根据JSON字符串生成T类型的对象
	 * @param json
	 * @param type
	 * @return
	 */
	public static <T> T parseJSON(String json,Class<T> type){
		Gson gson=new Gson();
		return gson.fromJson(json, type);
	}
	
	/**
	 * 将对象转换为JSON字符串
	 * @param obj
	 * @return
	 */
	public static String toJson(Object obj){
		
		Gson gson=new Gson();
		return gson.toJson(obj);
	}
	
	/**
	 * 获取系统根路径
	 * @return
	 */
	public static String getClassPath(){
		//获取绝对路径
		String classpath=Common.class.getResource("/").getPath();
		classpath=urlDecode(classpath,"UTF-8");
		if(classpath!=null && classpath.indexOf("/")==0){
			classpath=classpath.substring(1);
		}
		return classpath;
		
	}
	
	/**
	 * URL编码
	 * @param url
	 * @param charset
	 * @return
	 */
	public static String urlEncode(String url,String charset){
		try {
			return URLEncoder.encode(url, charset);
		} catch (UnsupportedEncodingException e) {
			_log.debug("URL Encoding 失败"+e.getMessage());
			return null;
		}
	}
	
	/**
	 * URL解码
	 * @param url
	 * @param charset
	 * @return
	 */
	public static String urlDecode(String url,String charset){
		
		try {
			return URLDecoder.decode(url, charset);
		} catch (UnsupportedEncodingException e) {
			_log.debug("URL Decode 失败"+e.getMessage());
			return null;
		}
	}
	
	public static void run(){
		String classpath=getClassPath();
		System.out.println(classpath);
	}

}
